<?php


namespace app\admin\controller;


use app\admin\controller\BaseController;
use app\common\model\mysql\PostsCategory as PostsCategoryModel;
use app\common\exception\MessageException;
use app\common\validate\NameValidate;

class PostsCategory extends BaseController
{
    public function list()
    {
        $pageSize = $this->request->param('pageSize');
        // 分页查询
        $User = new PostsCategoryModel();
        $list = $User->paginate($pageSize);
        return $this->renderSuccess(compact('list'));
    }

    public function create()
    {
        if (!$this->request->isPost()) {
            throw new MessageException(['msg' => '请求方法不合法']);
        }
        (new NameValidate())->goCheck();
        $data = $this->request->param();
        try {
            $Model = new PostsCategoryModel();
            $findData = $Model->checkName($data['name']);

            if ($findData) {
                // TODO 抛出异常未被捕获msg
                // throw new MessageException(['msg' => '分类名称已存在']);
                return $this->renderFail('分类名称已存在');
            }

            $data['status'] = 1;

            $admin = $Model->create($data);
            if ($admin) {
                return $this->renderSuccess([],'添加成功');
            }

        } catch (\Exception $e) {
            throw new MessageException(['msg' => $e->getMessage()]);
        }
    }

    public function update()
    {
        if (!$this->request->isPost()) {
            throw new MessageException(['msg' => '请求方法不合法']);
        }
        (new NameValidate())->goCheck();
        $data = $this->request->param();

        try {
            $Model = new PostsCategoryModel();
            $findData = $Model->checkName($data['name']);

            if ($findData) {
                // TODO 抛出异常未被捕获msg
                // throw new MessageException(['msg' => '分类名称已存在']);
                return $this->renderFail('分类名称已存在');
            }

            $admin = $Model->create($data);
            if ($admin) {
                return $this->renderSuccess([],'添加成功');
            }

        } catch (\Exception $e) {
            throw new MessageException(['msg' => $e->getMessage()]);
        }
    }

    public function delete()
    {

    }
}